<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { Check } from '@element-plus/icons-vue'
import { getEmailByUsername, loginByEmailCode } from '@/api/user'
import { useAuthStore, useUserProfileStore } from '@/store'

const router = useRouter()
const activeStep = ref(0)
const formRef = ref(null)
const isLoading = ref(false)
const countDown = ref(0)
const timer = ref(null)

// 表单数据
const form = reactive({
  username: '',
  verificationCode: '',
  password: '',
  confirmPassword: ''
})

// 用户信息
const userInfo = reactive({
  email: ''
})

// 表单规则
const rules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度应为3-20个字符', trigger: 'blur' }
  ],
  verificationCode: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { min: 6, max: 6, message: '验证码为6位数字', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 5, max: 20, message: '密码长度应为5-20个字符', trigger: 'blur' },
    { 
      message: '密码可以不包含大小写字母和数字', 
      trigger: 'blur'
    }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (value !== form.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      }, 
      trigger: 'blur' 
    }
  ]
})

// 控制当前步骤表单的显示
const showStep = computed(() => {
  return {
    step1: activeStep.value === 0,
    step2: activeStep.value === 1,
    step3: activeStep.value === 2
  }
})

// 按钮文本
const nextButtonText = computed(() => {
  switch (activeStep.value) {
    case 0: return '下一步'
    case 1: return '验证'
    case 2: return '重置密码'
    default: return '下一步'
  }
})

// 检查用户名
const checkUsername = async () => {
  isLoading.value = true
  try {
    // 调用获取邮箱API
    const res = await getEmailByUsername(form.username)
    console.log(res)
    if (res.status === 0) {
      // 对邮箱进行加密
      userInfo.email = res.data
      ElMessage.success(res.message)
    } else {
      ElMessage.error(res.message)
      return
    }
    // 进入下一步
    activeStep.value = 1
  } catch (error) {
    console.error(error)
  } finally {
    isLoading.value = false
  }
}

const authStore = useAuthStore()
// 发送验证码
const sendVerificationCode = async () => {
  if (countDown.value > 0) return
  
  try {
    // 调用发送验证码API
    await authStore.sendCode(userInfo.email)
    
    // 开始倒计时
    countDown.value = 60
    startCountDown()
  } catch (error) {
    ElMessage.error('发送验证码失败，请稍后重试')
    console.error(error)
  }
}

// 验证码倒计时
const startCountDown = () => {
  timer.value = setInterval(() => {
    if (countDown.value > 0) {
      countDown.value--
    } else {
      clearInterval(timer.value)
    }
  }, 1000)
}

// 验证验证码
const verifyCode = async () => {
  isLoading.value = true
  try {
    // 调用验证验证码API
    const res = await loginByEmailCode({ email: userInfo.email, code: form.verificationCode })
    if (res.status === 0) {
      ElMessage.success("验证码正确")
      // 进入下一步 重置密码
      activeStep.value = 2
    } else {
      ElMessage.error(res.message)
    }
  } catch (error) {
    ElMessage.error('验证码错误或已过期')
  } finally {
    isLoading.value = false
  }
}

const userProfileStore = useUserProfileStore()
// 重置密码
const resetPassword = async () => {
  isLoading.value = true
  try {
    // 调用设置密码API
    if (await userProfileStore.setPassword({
      username: form.username,
      password: form.password
    })) {
      // 重置完成后跳转到登录页
      setTimeout(() => {
        router.push('/login')
      }, 1000)
    } else {
      ElMessage.error('密码重置失败，请稍后重试')
    }
  } catch (error) {
    ElMessage.error('密码重置失败，请稍后重试')
  } finally {
    isLoading.value = false
  }
}

// 处理表单提交
const handleNext = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    switch (activeStep.value) {
      case 0:
        await checkUsername()
        break
      case 1:
        await verifyCode()
        break
      case 2:
        await resetPassword()
        break
    }
  } catch (error) {
    // 表单验证失败
    console.error('表单验证失败', error)
  }
}

// 返回上一步
const handlePrevious = () => {
  if (activeStep.value > 0) {
    activeStep.value--
  }
}

// 返回登录页
const goToLogin = () => {
  router.push('/login')
}
</script>

<template>
  <div class="forgot-password-container">
    <div class="forgot-password-card">
      <h2 class="title">找回密码</h2>
      
      <!-- 步骤条 -->
      <el-steps :active="activeStep" finish-status="success" simple class="steps">
        <el-step title="输入用户名" :icon="activeStep > 0 ? Check : ''"></el-step>
        <el-step title="验证身份" :icon="activeStep > 1 ? Check : ''"></el-step>
        <el-step title="重置密码" :icon="activeStep > 2 ? Check : ''"></el-step>
      </el-steps>
      
      <!-- 表单 -->
      <el-form 
        ref="formRef"
        :model="form"
        :rules="rules"
        label-position="top"
        class="password-form"
      >
        <!-- 步骤1：输入用户名 -->
        <div v-if="showStep.step1">
          <p class="step-description">请输入您的用户名，我们将发送验证码到您的邮箱。</p>
          
          <el-form-item prop="username" label="用户名">
            <el-input 
              @keyup.enter="handleNext"
              v-model="form.username"
              placeholder="请输入您注册时使用的用户名"
              :prefix-icon="User"
            ></el-input>
          </el-form-item>
        </div>
        
        <!-- 步骤2：验证身份 -->
        <div v-if="showStep.step2">
          <p class="step-description">验证码已发送至您的邮箱：<span class="email">{{ userInfo.email }}</span></p>
          
          <el-form-item prop="verificationCode" label="验证码">
            <div class="code-input-group">
              <el-input 
                v-model="form.verificationCode"
                placeholder="请输入6位验证码"
                maxlength="6"
              ></el-input>
              <el-button 
                type="primary"
                @click="sendVerificationCode"
                :disabled="countDown > 0"
                class="send-code-btn"
              >
                {{ countDown > 0 ? `重新发送(${countDown}s)` : '获取验证码' }}
              </el-button>
            </div>
          </el-form-item>
        </div>
        
        <!-- 步骤3：重置密码 -->
        <div v-if="showStep.step3">
          <p class="step-description">请设置您的新密码</p>
          
          <el-form-item prop="password" label="新密码">
            <el-input 
              v-model="form.password"
              type="password"
              placeholder="请输入新密码"
              show-password
            ></el-input>
          </el-form-item>
          
          <el-form-item prop="confirmPassword" label="确认密码">
            <el-input 
              v-model="form.confirmPassword"
              type="password"
              placeholder="请再次输入新密码"
              show-password
            ></el-input>
          </el-form-item>
          
          <div class="password-tips">
            <p>密码要求：</p>
            <ul>
              <li>长度为6-15个字符</li>
              <li>可以不包含大小写字母和数字</li>
            </ul>
          </div>
        </div>
        
        <!-- 按钮组 -->
        <div class="form-actions">
          <el-button class="back-btn" @click="goToLogin" v-if="activeStep === 0">返回登录</el-button>
          <el-button class="back-btn" @click="handlePrevious" v-if="activeStep > 0">上一步</el-button>
          <el-button 
            type="primary" 
            @click="handleNext"
            :loading="isLoading"
          >{{ nextButtonText }}</el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>

<style scoped>
.forgot-password-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: calc(100vh - 120px);
  background-color: #f5f5f5;
  padding: 20px;
}

.forgot-password-card {
  width: 100%;
  max-width: 610px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  padding: 30px;
}

.title {
  font-size: 24px;
  text-align: center;
  margin-bottom: 30px;
  color: #333;
}

.steps {
  margin-bottom: 30px;
}

.password-form {
  margin-top: 20px;
}

.step-description {
  margin-bottom: 20px;
  color: #606266;
  line-height: 1.5;
}

.email {
  font-weight: bold;
  color: var(--primary-color);
}

.code-input-group {
  display: flex;
  gap: 10px;
}

.send-code-btn {
  white-space: nowrap;
  min-width: 120px;
}

/* 发送验证码按钮禁用样式 */
.send-code-btn:disabled, .send-code-btn:disabled:hover {
  background-color: var(--primary-bg) !important;
  border-color: var(--primary-bg) !important;
  color: #c0c4cc !important;
  cursor: not-allowed;
}

.password-tips {
  background-color: #f8f8f8;
  border-radius: 4px;
  padding: 12px 16px;
  margin-top: 20px;
  margin-bottom: 20px;
  font-size: 13px;
  color: #606266;
}

.password-tips p {
  margin-top: 0;
  margin-bottom: 8px;
  color: #333;
  font-weight: 500;
}

.password-tips ul {
  margin: 0;
  padding-left: 20px;
}

.password-tips li {
  margin-bottom: 4px;
}

.form-actions {
  display: flex;
  justify-content: space-between;
  margin-top: 30px;
}

.el-button+.el-button {
  margin-left: 0px;
}

.back-btn {
  border-color: var(--primary-color);
  color: var(--primary-color);
}

.back-btn:hover {
  background-color: var(--primary-bg);
}

.el-button.is-disabled, .el-button.is-disabled:hover {
  background-color: var(--primary-bg);
}

@media (max-width: 576px) {
  .forgot-password-card {
    padding: 20px;
  }
  
  .code-input-group {
    flex-direction: column;
  }
  
  .send-code-btn {
    width: 100%;
  }
  
  .form-actions {
    flex-direction: column;
    gap: 10px;
  }
  
  .form-actions button {
    width: 100%;
  }
}
</style> 